<style lang="less">
@import "../../styles/common.less";
.blue-tag{
    margin:2px 4px;
    display: inline-block;
    padding:2px 6px;
    color:#fff;
    background:#2d8cf0;
}
</style>

<template>
  <div class="margin-top-10">
    <Row type="flex" justify="space-between">
      <Row>
        <!-- <Button type="primary" @click="handleAddClassgrade" style="margin-right: 3px">添加班级</Button> -->
      </Row>
      <Row>
        <Input
          v-model.trim="queryForm.name"
          @on-enter="searchClassgrade"
          placeholder="请输入班级名称"
          style="width: 150px;margin-right:3px"
        ></Input>
        <Input
          v-model.trim="queryForm.num"
          @on-enter="searchClassgrade"
          placeholder="请输入班级编号"
          style="width: 150px;margin-right:3px"
        ></Input>
        <Button @click="searchClassgrade" type="primary">查询</Button>
      </Row>
    </Row>
    <div class="margin-top-10">
      <Table :columns="classgradeColumn" :data="classgradeData" :loading="tableLoading"></Table>
    </div>
    <Row type="flex" justify="end" class="margin-top-10">
      <Page
        :total="totalClassgrade"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="getClassgrade"
        show-total
      >显示第{{currentIndex + 1}}-{{currentIndex + pageSize}}条，总数为{{totalClassgrade}}条</Page>
    </Row>

    <Modal
      v-model="addClassgradeModal"
      v-bind:title="modalTitle"
      :scrollable="true"
      class-name="vertical-center-modal"
      :mask-closable="false"
      @on-cancel="resetForm('classgradeInfoForm')"
    >
      <Form
        ref="classgradeInfoForm"
        :label-width="80"
        :model="classgradeInfo"
        :rules="classgradeInfoRules"
      >
        <FormItem label="班级名称" prop="name">
            <Input v-model.trim="classgradeInfo.name" placeholder="请填写班级名称" />
        </FormItem>
        <FormItem label="班级编号" prop="num">
            <Input
            placeholder="请填写班级编号"
            style="width: 100%"
            v-model.trim="classgradeInfo.num"
            />
        </FormItem>
        <FormItem label="班级学生" prop="student_ids">
            <!-- <Input placeholder="请填写班级学生" v-model.trim="classgradeInfo.related_students" /> -->
            <CheckboxGroup v-model="classgradeInfo.student_ids">
                <Checkbox :label="item._id" v-for="item in studentList" :key="item._id">
                    <span>{{item.user_name}}({{item.user_num}})</span>
                </Checkbox>
            </CheckboxGroup>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="handleSubmitClassgrade('classgradeInfoForm')">提交</Button>
      </div>
    </Modal>

    <!-- 查看学生 -->
    <Modal
        v-model="studentModal"
        title="学生列表">
        <Table :columns="studentColumn" :data="studentTableData"></Table>
        <div slot="footer">

        </div>
    </Modal>

    <!-- <Modal v-model="uploadModal" @on-cancel="hideUploadModal">
      <div slot="header">
        <p>
          导入表格
          <span style="font-weight: 100;font-size: 12px;margin-left: 5px">
            (请严格按照
            <a :href="excelFile" download="模板.xlsx">模板</a>格式上传表格)
          </span>
        </p>
      </div>
      <HorizonUploader ref="uploader"></HorizonUploader>
      <div slot="footer">
        <Button type="primary" @click="handleUpload">上传</Button>
      </div>
    </Modal> -->
  </div>
</template>

<script>
import {
  getClassgrade,
  addClassgrade,
  updateClassgrade,
  deleteClassgrade,
} from "../../controllers/classgrade";
import { getStudentData } from '../../controllers/student';
import HorizonUploader from "./components/HorizonUploader.vue";

import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip";
import Btn from "../../../node_modules/iview/src/components/button/button";
import Constant from "../../libs/constants";
import _ from "lodash";
import iconDelete from "../../images/delete.png";
import iconEdit from "../../images/edit.png";

import excelFile from "../../assets/staffExcel.xlsx";

export default {
  name:'classgrade',
  components: {
    HorizonUploader,
    Tooltip,
    Btn
  },
  data() {
    return {
      addClassgradeModal: false,
      tableLoading: true,
      queryForm:{
          name:'',
          num:''
      },
      pageSize: Constant.PAGE_SIZE,
      currentPage: 1,
      totalClassgrade: 0,
      classgradeColumn: [
        {
          title: "班级名称",
          align: "center",
          key: "name",
          width: 300
        },
        {
          title: "班级编号",
          key: "num",
          align: "center",
          width: 300
        },
        // {
        //   title: "班级学生",
        //   align: "center",
        //   minWidth: 400,
        //   render: (h, {row, column, index}) => {
        //       const students = row.related_students;
        //       return (
        //           <div>
        //             {
        //                 students.map(item=>{
        //                     return (
        //                         <span class="blue-tag">{item.student_name}({item.student_num})</span>
        //                     )
        //                 })
        //             }
        //           </div>
        //       )
        //   }
        // },
        {
          title: "操作",
          align: "center",
          minWidth: 240,
          render: (h, { row, column, index }) => {
            const _id = row._id;
            return (
              <div class="operate-column">
                {
                  /*
                    <Tooltip content="编辑" placement="bottom">
                      <Btn
                        style={{ background: `url( ${iconEdit})` }}
                        onClick={() => this.handleEditClassgrade(row)}
                      />
                    </Tooltip>
                    <Tooltip content="删除" placement="bottom">
                      <Btn
                        style={{ background: `url( ${iconDelete})` }}
                        onClick={() => this.handleDelClassgrade(_id, row.name)}
                      />
                    </Tooltip>
                  */
                }
                <Btn type="text" onClick={() => this.handleViewStudents(row)}>查看学生</Btn>
              </div>
            );
          }
        }
      ],
      classgradeData: [],
      studentList:[],
      classgradeInfo: {
        _id:'',
        name:'',
        num:'',
        student_ids:[]
      },
      modalTitle: "添加正式员工",
      classgradeInfoRules: {
          name: [
            { required: true, message: "请输入班级名称", trigger: "blur" }
          ],
          num: [
              {required: true, message: "请输入班级编号", trigger: "blur"}
          ],
        //   student_ids: [
        //       {required: true, message: "请选择关联的学生", trigger: "blur"}
        //   ],
      },
      uploadModal: false,
      excelFile: excelFile,

      studentModal:false,
      studentTableData:[],
      studentColumn:[
        {
          title:'学号',
          key:'student_num',
          align:'center'
        },
        {
          title:'姓名',
          key:'student_name',
          align:'center'
        }
      ]
    };
  },
  computed: {
    currentIndex: function() {
      return (this.currentPage - 1) * this.pageSize;
    },
  },
  //待考虑：初次加载表格的时机
  created() {
    this.loadclassgradeData();
    this.getStudentList();
  },
  methods: {
    getClassgrade(page) {
      this.currentPage = page;
      this.tableLoading = true;
      this.loadclassgradeData();
    },
    getStudentList(){
        getStudentData(1,1000).then(res=>{
            this.studentList = res.data.result || []
        })
    },
    handleAddClassgrade(type) {
      this.modalTitle = "添加班级";
      this.classgradeInfo._id = null;
      this.addClassgradeModal = true;
      if(this.studentList.length===0){
          this.getStudentList()
      }
    },
    handleSubmitClassgrade(form) {
      const submitInfo = Object.assign({},this.classgradeInfo)
      this.$refs[form].validate(valid => {
        if (valid) {
          if(submitInfo._id){
            updateClassgrade(
                submitInfo
            ).then(res => {
                if (res.code == 0) {
                this.$Message.success("提交成功!");
                this.addClassgradeModal = false;
                this.resetForm(form);
                this.getClassgrade(this.currentPage);
                }
            });
          }else{
            addClassgrade(
              submitInfo
            ).then(res => {
              if (res.code == 0) {
                this.$Message.success("提交成功!");
                this.addClassgradeModal = false;
                this.resetForm(form);
                this.getClassgrade(this.currentPage);
              }
            });
          }
        } else {
          this.$Message.error("填写项目验证失败!");
        }
      });
    },
    handleDelClassgrade(id, name) {
      this.$Modal.confirm({
        title: "确认",
        content: "删除班级【" + name + "】？",
        onOk: () => {
          // 删除基本信息
          deleteClassgrade({ _id: [id] }).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.getClassgrade(this.currentPage);
            }
          });
        }
      });
    },
    handleEditClassgrade(row) {
      const data = row || {};
      this.modalTitle = "编辑班级";
      this.classgradeInfo._id = data._id;
      this.classgradeInfo.name = data.name;
      this.classgradeInfo.num = data.num;
      this.classgradeInfo.student_ids = data.related_students.map(item=>item.student_id);
      this.addClassgradeModal = true;
      if(this.studentList.length===0){
          this.getStudentList()
      }
    },
    handleViewStudents(row){
      const students = row.related_students
      this.studentModal = true;
      this.studentTableData = students;
    },
    searchClassgrade() {
      //to-do:检验关键词
      this.currentPage = 1;
      this.tableLoading = true;
      this.loadclassgradeData();
    },
    loadclassgradeData() {
      getClassgrade({
          page_num:this.currentPage, 
          page_size:this.pageSize, 
          ...this.queryForm
        })
        .then(json => {
          let { total, data } = transclassgradeData(json);
          this.totalClassgrade = total;
          this.classgradeData = data;
          this.tableLoading = false;
          let tmp = _.map(data, item => item.uid);
          return tmp;
        })
        // .then(uids => this.asyncAvatar(uids));
    },
    resetForm(form) {
      //解决对话框消失的时候字体变化问题
      setTimeout(() => {
        this.$refs[form].resetFields();
        this.classgradeInfo._id = null;
      }, 500);
    },
    handleUpload() {
      if (!this.$refs["uploader"].hasFile) {
        this.$Message.error("请先选择文件");
        return;
      }
      var formData = new FormData();
      formData.append("file", this.$refs["uploader"].file);
      uploadclassgradeData(formData).then(json => {
        if (json.code == 0) {
          this.$Message.success(json.msg);
          this.hideUploadModal();
          this.getClassgrade(this.currentPage);
        }
      });
    },
    hideUploadModal() {
      this.$refs["uploader"].reset();
      this.uploadModal = false;
    },
  }
};

function transclassgradeData(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { total: 0, result: {} };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined) {
    return { total: 0, result: {} };
  }

  let { total, result } = data;

  return {
    total,
    data: result
  };
}

</script>